<script setup lang="ts">
import { computed } from "vue";
import payWechatIcon from "~/assets/pay-wechat.png";
import payAlipayIcon from "~/assets/pay-ali.png";
import payCardIcon from "~/assets/pay-card.png";
import { ElMessage } from "element-plus";
import { RefreshRight } from "@element-plus/icons-vue";
import { createWalletRechargeOrderAPI, getWalletSummaryAPI, queryWalletRechargeStatusAPI } from "~/api/wallet";
import { queryRiseStatus } from "~/api/goods";

// 声明全局QRCode类型
declare global {
  interface Window {
    QRCode: any;
  }
}

const emits = defineEmits(["close", "success"]);

const closeDialog = () => {
  emits("close");
};

// 输入金额（元）
const amountYuan = ref<string>("");

// 支付方式：使用字符串枚举值
const payType = ref<string>("WECHAT");
const payWays = [
  { label: "微信支付", value: "WECHAT", icon: payWechatIcon, desc: "即时到账" },
  { label: "支付宝", value: "ALIPAY", icon: payAlipayIcon, desc: "大额专享" },
  { label: "企业网银", value: "ENTERPRISE_PAY", icon: payCardIcon, desc: "推荐企业使用" },
  { label: "线下汇款", value: "OFFLINE_REMIT", icon: payCardIcon, desc: "转账至平台账户" },
];

const selecting = (v: string) => {
  payType.value = v;
  // 切换支付方式时，隐藏二维码区
  showQr.value = false;
};

// 二维码区
const showQr = ref(false);
const expireTimeText = ref("");
const timer = ref<any>(null);
const qrUrl = ref("");
const end = ref(false);
const rechargeOrderNo = ref("");
const preAvailableBalance = ref<number | null>(null);
const payChannel = computed(() => {
  switch (payType.value) {
    case "WECHAT": return "weixin";
    case "ALIPAY": return "alipay";
    default: return "";
  }
});

// 计算属性：是否已过期
const isExpired = computed(() => expireTimeText.value === '已过期');

// 倒计时展示，统一15分钟有效
const setExpireCountdown = () => {
  const end = Date.now() + 15 * 60 * 1000;
  if (timer.value) clearInterval(timer.value);
  timer.value = setInterval(() => {
    const diff = end - Date.now();
    if (diff <= 0) {
      expireTimeText.value = "已过期";
      clearInterval(timer.value);
    } else {
      const m = Math.floor(diff / 60000);
      const s = Math.floor((diff % 60000) / 1000);
      expireTimeText.value = `${m}分${s}秒`;
    }
  }, 1000);
};

// 简化的URL验证函数（只用于微信二维码）
const validateWechatUrl = (url: string) => {
  if (!url || typeof url !== 'string') {
    return '';
  }

  const cleanedUrl = url.trim();

  // 验证微信支付URL格式
  if (cleanedUrl.startsWith('weixin://') ||
      cleanedUrl.startsWith('https://') ||
      cleanedUrl.startsWith('http://')) {
    return cleanedUrl;
  }

  return '';
};

// 生成二维码
const renderQRCode = () => {
  console.log("开始生成二维码...");
  console.log("支付类型:", payType.value);
  console.log("原始url:", qrUrl.value);

  // 支付宝使用iframe展示，不需要生成二维码
  if (payType.value === "ALIPAY") {
    console.log("支付宝支付，使用iframe展示");
    return;
  }

  // 微信支付才需要生成二维码
  if (payType.value === "WECHAT") {
    // 验证微信URL
    const cleanedUrl = validateWechatUrl(qrUrl.value);
    console.log("验证后的url:", cleanedUrl);

    const el = document.getElementById("wallet-qrcode");
    if (!el) return;

    el.innerHTML = "";

    // 检查QRCode库是否已加载，如果没有则等待
    let retryCount = 0;
    const maxRetries = 10; // 最多重试10次，总共5秒

    const checkQRCodeLibrary = () => {
      if (typeof window !== 'undefined' && window.QRCode && cleanedUrl) {
        console.log("QRCode库已加载，开始生成微信二维码");
        try {
          new window.QRCode("wallet-qrcode", {
            text: cleanedUrl,
            width: 152,
            height: 152,
            colorDark: "#000",
            colorLight: "#fff",
            correctLevel: window.QRCode.CorrectLevel.H,
          });
          console.log("微信二维码生成成功");
        } catch (e) {
          console.error("二维码生成失败", e);
          el.innerHTML = `<div style="padding: 20px;text-align:center;font-size:12px;color:#666;">二维码生成失败<br/>${cleanedUrl}</div>`;
        }
      } else if (!cleanedUrl) {
        console.error("URL无效");
        el.innerHTML = `<div style="padding: 20px;text-align:center;font-size:12px;color:#666;">支付链接无效<br/>请重新获取</div>`;
      } else if (retryCount < maxRetries) {
        retryCount++;
        console.log(`QRCode库尚未加载，第${retryCount}次重试，等待500ms后重试...`);
        setTimeout(checkQRCodeLibrary, 500);
      } else {
        console.error("QRCode库加载超时，使用备用方案");
        // 使用备用的在线二维码生成服务
        const qrApiUrl = `https://api.qrserver.com/v1/create-qr-code/?size=152x152&data=${encodeURIComponent(cleanedUrl)}`;
        el.innerHTML = `<img src="${qrApiUrl}" alt="支付二维码" style="width: 152px; height: 152px;" onerror="this.style.display='none'; this.nextElementSibling.style.display='block';" /><div style="display:none; padding: 20px;text-align:center;font-size:12px;color:#666;">二维码加载失败<br/>请刷新页面重试</div>`;
      }
    };

    // 开始检查QRCode库
    checkQRCodeLibrary();
  }
};

// 刷新二维码：重新创建订单
const refreshQRCode = async () => {
  if (!amountYuan.value) {
    ElMessage.warning("请先输入充值金额");
    return;
  }
  await createRechargeOrder();
};

// 创建充值订单
const creating = ref(false);
const createRechargeOrder = async () => {
  const amt = Number(amountYuan.value);
  if (!amt || amt <= 0) {
    ElMessage.warning("请输入正确的充值金额");
    return;
  }
  creating.value = true;
  try {
    const params = {
      amount: amt, // 直接使用元为单位，不再乘以100
      payType: payType.value,
      paymentScene: "QRCODE",
      remark: "企业账户充值",
    } as any;
    console.log('发送的充值参数:', params); // 添加调试日志
    const res = await createWalletRechargeOrderAPI(params);
    console.log("充值订单API返回结果:", res);

    // 兼容不同返回结构：payUrl 或 qrCode 或 payParams.qrCode
    const data = res?.data || {};
    const url = data.payUrl || data.qrCode || data.payParams?.qrCode || "";
    console.log("提取的支付URL:", url);

    if (!url) {
      console.error("API返回的支付URL为空");
      ElMessage.error("获取支付链接失败，请重试");
      return;
    }

    qrUrl.value = url;
    rechargeOrderNo.value = data.rechargeOrderNo || data.orderSn || data.tradeNo || "";

    if (payType.value === "WECHAT" || payType.value === "ALIPAY") {
      // 扫码支付（微信/支付宝）
      showQr.value = true;
      nextTick(() => {
        renderQRCode();
      });
      setExpireCountdown();
      await startRechargePolling();
    } else {
      // 企业支付/线下支付：下单成功提示
      showQr.value = false;
      ElMessage.success("已创建企业支付订单，请按指引完成转账");
      emits("success");
      closeDialog();
    }
  } catch (e) {
    console.error(e);
    ElMessage.error(resMsg(e) || "创建充值订单失败");
  } finally {
    creating.value = false;
  }
};

const resMsg = (e: any) => {
  try {
    return e?.message || e?.msg || e?.data?.msg;
  } catch {
    return "";
  }
};

onUnmounted(() => {
  if (timer.value) clearInterval(timer.value);
  end.value = true;
});

const startRechargePolling = async () => {
  try {
    const { data } = await getWalletSummaryAPI({});
    preAvailableBalance.value = Number(data?.availableBalance ?? 0);
  } catch (e) {
    preAvailableBalance.value = null;
  }
  pollRechargeStatus();
};

const pollRechargeStatus = async () => {
  if (end.value || isExpired.value) return;
  try {
    if (rechargeOrderNo.value) {
      try {
        const statusResRise = await queryRiseStatus({ orderSn: rechargeOrderNo.value, goodsId: "" });
        if (statusResRise && statusResRise.data && Number(statusResRise.data.status) === 1) {
          emits("success");
          closeDialog();
          return;
        }
      } catch (e) {
      }
    }
    if (rechargeOrderNo.value) {
      try {
        const statusRes = await queryWalletRechargeStatusAPI({ orderNo: rechargeOrderNo.value });
        if (statusRes && statusRes.data && Number(statusRes.data.status) === 1) {
          emits("success");
          closeDialog();
          return;
        }
      } catch (e) {
      }
    }
    const { data } = await getWalletSummaryAPI({});
    const cur = Number(data?.availableBalance ?? 0);
    const amt = Number(amountYuan.value);
    if (preAvailableBalance.value != null && amt > 0 && cur - preAvailableBalance.value >= amt - 0.0001) {
      emits("success");
      closeDialog();
      return;
    }
  } catch (e) {
  }
  if (!end.value) {
    setTimeout(pollRechargeStatus, 3000);
  }
};
</script>

<template>
  <div class="dialog-mask" @click="closeDialog">
    <div class="dialog-box" @click.stop>
      <div class="header">
        <div class="left">
          <img src="~/assets/dialog-icon.png" alt="" />
          <span>企业账户充值</span>
        </div>
        <img class="close" src="~/assets/modal-close.png" alt="" @click="closeDialog" />
      </div>

      <div class="body">
        <div class="amount-row" v-if="!showQr">
          <el-input v-model="amountYuan" placeholder="请输入充值金额（元）"></el-input>
          <el-button type="primary" class="go-pay" :loading="creating" @click="createRechargeOrder">充值</el-button>
        </div>

        <p class="tips" v-if="!showQr">请选择支付方式</p>
        <div class="pay-list" v-if="!showQr">
          <div class="pay-item" :class="{checked: payType===item.value}" v-for="item in payWays" :key="item.value" @click="selecting(item.value)">
            <img :src="item.icon" />
            <div class="info">
              <span class="name">{{ item.label }}</span>
              <span class="desc">{{ item.desc }}</span>
            </div>
            <div class="checked"><span></span></div>
          </div>
        </div>

        <!-- 扫码支付区 -->
        <div v-if="showQr" class="qr-wrapper">
          <p class="title">请使用{{ payChannel === 'weixin' ? '微信' : '支付宝' }}扫码支付</p>

          <!-- 微信支付：使用 QRCode 生成二维码 -->
          <div v-if="payChannel === 'weixin'" class="qr-container">
            <div id="wallet-qrcode"></div>
            <div v-if="isExpired" class="expire-mask">已过期</div>
          </div>

          <!-- 支付宝支付：使用 iframe 展示 -->
          <div v-if="payChannel === 'alipay'" class="qr-container">
            <iframe
              class="pay-qrcode-ali"
              :srcdoc="qrUrl"
              frameborder="0"
              marginwidth="0"
              marginheight="0"
              scrolling="no"
              width="152"
              height="152"
            >
            </iframe>
            <div v-if="isExpired" class="expire-mask">已过期</div>
          </div>

          <p class="expire-tips">
            {{ isExpired ? '' : '距离二维码过期还剩' }}
            <span>{{ isExpired ? '' : expireTimeText }}</span>
          </p>
          <p class="refresh" @click="refreshQRCode">
            <el-icon><RefreshRight /></el-icon> 刷新
          </p>
        </div>
      </div>
    </div>
  </div>
 </template>

<style scoped lang="scss">
.dialog-mask {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(25, 30, 40, 0.4);
  z-index: 999;
  display: flex; align-items: center; justify-content: center;
}
.dialog-box {
  width: 480px;
  background: #fff;
  border-radius: 16px;
  padding: 24px;
}
.header { display:flex; align-items:center; margin-bottom: 16px; }
.header .left { flex:1; display:flex; align-items:center; }
.header .left img { width: 20px; height: 20px; margin-right: 4px; }
.header .left span { font-size: 16px; font-weight: bold; }
.header .close { width: 18px; height: 18px; cursor: pointer; }

.amount-row { display:flex; gap: 12px; margin-bottom: 16px; }
.go-pay { background: #1DBF73; border-color: #1DBF73; }
.tips { color: rgba(25,30,40,.48); margin: 8px 0; }

.pay-list { display:flex; flex-direction: column; gap: 8px; }
.pay-item {
  display:flex;
  align-items:center;
  border: 1px solid rgba(25,30,40,.08);
  border-radius: 8px;
  padding: 12px;
  cursor:pointer;
  transition: all 0.3s ease;
  position: relative;
}
.pay-item:hover {
  border-color: rgba(29, 191, 115, 0.3);
  background-color: rgba(29, 191, 115, 0.02);
}
.pay-item img { width: 32px; height: 32px; margin-right: 12px; }
.pay-item .info { display:flex; flex-direction:column; flex:1; }
.pay-item .name { color:#191E28; font-weight: 600; }
.pay-item .desc { font-size:12px; color:#999; }
.pay-item.checked {
  border: 2px solid #1DBF73;
  background-color: rgba(29, 191, 115, 0.05);
  box-shadow: 0 0 16px 0 rgba(29, 191, 115, 0.15);
}
.pay-item.checked::after {
  content: '';
  position: absolute;
  top: 0px;
  right: -1px;
  width: 0;
  height: 0;
  border-left: 31px solid transparent;
  border-top: 25px solid #1DBF73;
  border-top-right-radius: 8px;
}
.pay-item.checked::before {
  content: '✓';
  position: absolute;
  top: 1px;
  right: 3px;
  color: white;
  font-size: 12px;
  font-weight: bold;
  z-index: 1;
  line-height: 1;
}

.qr-wrapper { display:flex; flex-direction:column; align-items:center; }
.qr-wrapper .title { color:#191E28; font-size:18px; font-weight:bold; margin-bottom: 16px; }

.qr-container {
  width: 172px;
  height: 172px;
  margin-bottom: 16px;
  border-radius: 16px;
  border: 1px solid #e5e5e5;
  padding: 10px;
  box-sizing: border-box;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

#wallet-qrcode { width: 152px; height: 152px; }

.expire-mask {
  color: #ff4f4f;
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 2;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16px;
}

.expire-tips { color: rgba(25,30,40,.48); margin-bottom: 8px; text-align: center; }
.expire-tips span { color: #ff4f4f; }

.refresh {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #1DBF73;
  cursor: pointer;
  font-size: 14px;
}
</style>
